import os
from pathlib import Path
from flask import request, jsonify
from flask import Blueprint, send_from_directory
from .utils.response import JsonResponse
from .config import Config

bp = Blueprint("main", __name__)


def list_subfolders(directory):
    if not Path(directory).is_dir():
        raise NotADirectoryError(f"{directory} is not a valid directory.")

    try:
        subfolders = [
            d
            for d in os.listdir(directory)
            if Path(Path(directory).joinpath(d)).is_dir()
        ]
    except Exception as e:
        # 对可能的异常进行捕获和处理，让程序更加健壮
        print(f"An error occurred while listing subfolders: {e}")
        subfolders = []

    return subfolders


def get_first_file_name(directory):
    try:
        files = os.listdir(directory)
        if files:  # 检查文件夹内是否有文件
            first_file = files[0]
            return first_file
        else:
            return None  # 文件夹为空，返回 None 或自定义提示
    except FileNotFoundError:
        return f"Directory {directory} not found."


# 用于验证目录名和文件名的安全函数
def is_safe_path_component(component):
    # 避免路径遍历攻击，不允许包含'..'或'.'，以及其他不安全字符
    return not component.startswith("..") and not component.startswith(".")
    # return not re.search(r'\.\.|/|\\|:\*?"<>', component)


@bp.route("/")
def index():
    return "hello world"


@bp.route("/photos/getFolderList")
def getFolderList():
    results = []
    root_dir = Path(Config.PHOTO_PATH).resolve()
    folders = list_subfolders(root_dir)
    for folder in folders:
        first_file = get_first_file_name(Path(root_dir).joinpath(folder))
        result = {}
        result["folderName"] = folder
        result["fileTotal"] = len(os.listdir(Path(root_dir).joinpath(folder)))
        if first_file:
            result["fileName"] = first_file
            result["fileUrl"] = f"http://192.168.3.61:5000/image/{folder}/{first_file}"
        results.append(result)

    print(results)

    return JsonResponse(0, results).to_response()


@bp.route("/photos/getFileList/<string:folder>")
def getFileList(folder):
    # 检查folder参数是否安全
    if not is_safe_path_component(folder):
        return jsonify({"error": "Invalid folder name"}), 400

    try:
        # 获取文件列表
        file_list = os.listdir(Path(Config.PHOTO_PATH).joinpath(folder))
    except FileNotFoundError:
        return jsonify({"error": "Folder not found"}), 404
    except PermissionError:
        return jsonify({"error": "Permission denied"}), 403

    # 使用列表推导式构建结果
    results = [
        {"fileName": file, "fileUrl": f"http://192.168.3.61:5000/image/{folder}/{file}"}
        for file in file_list
        if is_safe_path_component(file)
    ]

    return JsonResponse(0, results).to_response()


@bp.route("/image/<string:folder>/<string:filename>")
def getImage(folder, filename):
    image_path = Path(Config.PHOTO_PATH).joinpath(folder)
    print(f"getImage: {image_path}, filename: {filename}")
    return send_from_directory(image_path, filename)
